require "import"
import "android.widget.*"
import "android.content.Intent"
import "android.net.Uri"
import "android.text.SpannableString"
import "android.text.style.ForegroundColorSpan"
import "android.graphics.Color"
import "android.text.Spannable"
import "android.view.Gravity"
import "android.view.View"
import "java.util.Locale"
import "android.app.AlertDialog"

local utf8 = require("utf8")
local lang = tostring(Locale.getDefault().getLanguage())
local isFr = lang == "fr"

local STR = {
  dev = isFr and "Développé par: Saif Fathi" or "تم تطويره بواسطة: سايح فتحي",
  title = isFr and "Analyse du Texte" or "تحليل النص",
  hint = isFr and "Entrez le texte..." or "أدخل النص هنا...",
  exit = isFr and "Quitter" or "خروج",
  back = isFr and "Retour" or "رجوع",
  copy = isFr and "Copier" or "نسخ",
  delete = isFr and "Supprimer" or "حذف",
  replace = isFr and "Remplacer" or "استبدال",
  channel = isFr and "Chaîne Masirat Al-Kafif" or "قناة مسيرة الكفيف",
  no_items = isFr and "Aucun élément" or "لا توجد عناصر",
  edit_title = isFr and "Action" or "إجراء",
  labels = {
    isFr and "Caractères" or "عدد الحروف",
    isFr and "Mots" or "عدد الكلمات",
    isFr and "Lignes" or "عدد الأسطر",
    isFr and "Phrases" or "عدد الجمل",
    isFr and "Symboles" or "عدد الرموز",
    isFr and "Minuscules" or "الحروف الصغيرة",
    isFr and "Majuscules" or "الحروف الكبيرة",
    isFr and "Chiffres" or "عدد الأرقام",
    isFr and "Emojis" or "عدد الإيموجي",
    isFr and "Mots répétés" or "كلمات مكررة",
    isFr and "Chiffres répétés" or "أرقام مكررة",
    isFr and "Emojis répétés" or "إيموجي مكرر"
  }
}

function showSelectionDialog(title, items, textInput)
  if #items == 0 then print(STR.no_items) return end
  local listView = ListView(this)
  local adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, items)
  listView.setAdapter(adapter)
  local dlg = LuaDialog(this)
  dlg.setTitle(title)
  dlg.setNeutralButton(STR.back, function() end)
  dlg.setView(listView)
  listView.onItemClick = function(l, v, p, i)
    local selectedWord = tostring(items[p + 1])
    local subDlg = LuaDialog(this)
    subDlg.setTitle(STR.edit_title)
    subDlg.setPositiveButton(STR.copy, function()
      service.copy(selectedWord)
      subDlg.dismiss()
    end)
    subDlg.setNegativeButton(STR.delete, function()
      local currentText = tostring(textInput.getText())
      textInput.setText(tostring(currentText:gsub(selectedWord, "")))
      subDlg.dismiss()
    end)
    subDlg.setNeutralButton(STR.replace, function()
      local editInput = EditText(this)
      editInput.setText(selectedWord)
      local editDlg = LuaDialog(this)
      editDlg.setTitle(STR.replace)
      editDlg.setView(editInput)
      editDlg.setButton("OK", function()
        local newWord = tostring(editInput.getText())
        local currentText = tostring(textInput.getText())
        textInput.setText(tostring(currentText:gsub(selectedWord, newWord)))
        editDlg.dismiss()
      end)
      editDlg.show()
      subDlg.dismiss()
    end)
    subDlg.show()
  end
  dlg.show()
end

function createStyledText(label, value)
  local text = label .. ": " .. tostring(value)
  local spannable = SpannableString(text)
  local labelLength = utf8.len(label) + 2
  spannable.setSpan(ForegroundColorSpan(Color.CYAN), 0, labelLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
  spannable.setSpan(ForegroundColorSpan(Color.WHITE), labelLength, utf8.len(text), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
  return spannable
end

function updateTextViews(textInput, textViews)
  local text = tostring(textInput.getText())
  local data = {chars={}, words={}, lines={}, sents={}, syms={}, lows={}, ups={}, nums={}, emos={}}
  for p, code in utf8.codes(text) do
    table.insert(data.chars, utf8.char(code))
  end
  for w in text:gmatch("%S+") do table.insert(data.words, w) end
  local values = {data.chars, data.words, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}
  for i=1, #STR.labels do
    if textViews[i] then
      textViews[i].setText(createStyledText(STR.labels[i], #values[i]))
      textViews[i].onClick = function() showSelectionDialog(STR.labels[i], values[i], textInput) end
    end
  end
end

function createAnalysisDialog()
  local initialText = tostring(service.getText(node) or "")
  local textViews = {}
  local layout = {ScrollView, layout_width="fill", layout_height="fill", backgroundColor=Color.BLACK, padding="16dp", {LinearLayout, orientation="vertical", layout_width="fill",
    {TextView, text=STR.dev, textSize="12sp", textColor=Color.GRAY, gravity="center"},
    {EditText, id="textInput", text=initialText, hint=STR.hint, backgroundColor=Color.DKGRAY, textColor=Color.WHITE, lines=3},
    {LinearLayout, id="listContainer", orientation="vertical", layout_width="fill", paddingTop="10dp"},
    {Button, text=STR.channel, backgroundColor=Color.BLUE, textColor=Color.WHITE, onClick=function()
      local uri = Uri.parse("https://t.me/+HeFqONqqeggxMmM8")
      local intent = Intent(Intent.ACTION_VIEW, uri)
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
      this.startActivity(intent)
      thinhdlg.dismiss()
    end},
    {Button, text=STR.exit, backgroundColor=Color.RED, textColor=Color.WHITE, onClick=function() thinhdlg.dismiss() end}}}
  thinhdlg = LuaDialog(this)
  thinhdlg.setView(loadlayout(layout))
  for _, n in ipairs(STR.labels) do
    local tv = TextView(this)
    tv.setPadding(10, 20, 10, 20)
    tv.setClickable(true)
    listContainer.addView(tv)
    table.insert(textViews, tv)
  end
  textInput.addTextChangedListener{onTextChanged=function() updateTextViews(textInput, textViews) end}
  updateTextViews(textInput, textViews)
  thinhdlg.show()
end

createAnalysisDialog()